package gen.tools.svn;

import gen.tools.Widgets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.GsonBuilder;

public class QuerySVNfileInJsonBySubsys extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public QuerySVNfileInJsonBySubsys() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		response.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		
		final String subsysId= request.getParameter("subsysId");
		final boolean isMR= Boolean.valueOf(request.getParameter("isMR"));
		final String modId = request.getParameter("modId");
		String res=null;
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			conn = wid.getConn();
			final String strSQL = "SELECT olSVNpath,mrSVNpath FROM modunits WHERE modUnitId=? AND subsysId=?";
			ps = conn.prepareStatement(strSQL);
			ps.setString(1, modId);
			ps.setString(2, subsysId);
			rs = ps.executeQuery();
			rs.next();
			if( isMR) {
				res = rs.getString("mrSVNpath");
			} else {
				res = rs.getString("olSVNpath");
			}
			
			ArrayList<String> connSVNInfo = null;
			if ( isMR ) {
				connSVNInfo = wid.getSVN4SubsysConnInfo(subsysId,3);
			} else {
				connSVNInfo = wid.getSVN4SubsysConnInfo(subsysId,4);
			}
			
			res = wid.getSVN2fileTreeJSON(connSVNInfo.get(0)+res, connSVNInfo.get(1), connSVNInfo.get(2));
		} catch (Exception e) {
			wid.errLog(e);
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		response.getWriter().write( new GsonBuilder().disableHtmlEscaping().create().toJson( res ).replaceAll("'", "\"") );
	}

}
